package top.xana.acg.anime.ui.page

import android.os.Bundle
import androidx.fragment.app.activityViewModels
import com.drake.brv.utils.grid
import com.drake.brv.utils.setup
import top.xana.acg.anime.BR
import top.xana.acg.anime.R
import top.xana.acg.anime.SearchSource
import top.xana.acg.anime.databinding.FragmentCategoryBinding
import top.xana.acg.anime.model.Anime
import top.xana.acg.anime.ui.viewmodel.AnimeViewModel
import top.xana.acg.base.BaseFragment
import top.xana.acg.anime.utils.navTo

class CategoryFragment : BaseFragment<FragmentCategoryBinding>(R.layout.fragment_category) {

    companion object {
        @JvmStatic
        fun newInstance(i: Int) = CategoryFragment().apply {
            arguments = Bundle().apply {
                putInt(KEY, i)
            }
        }

        const val TAG = "CategoryFragment"
        const val KEY = "KEY_INDEX"
    }

    private var keyIndex = 0

    private var page = 0

    private val viewModel by activityViewModels<AnimeViewModel>()

    override fun initArgs(bundle: Bundle?) {
        super.initArgs(bundle)
        arguments?.let {
            keyIndex = it.getInt(KEY)
        }
    }



    override fun initView() {
        super.initView()
        binding.listView.grid(3).setup {
            addType<Anime>(R.layout.item_category_anime_view)
            onBind {
                modelId = BR.anime
            }
            onClick(R.id.frameAnime) {
                itemView.navTo(
                    R.id.toPagePlayer,
                    AnimePlayerFragment.createBundle(SearchSource.Bimi, getModel())
                )
            }
        }
        binding.page.onRefresh {
            page = 0
            viewModel.loadHomeCate(keyIndex, page, this::addData)
        }.onLoadMore {
            viewModel.loadHomeCate(keyIndex, ++page) {
                addData(it) { it.isNotEmpty() }
            }
        }.autoRefresh()
    }

}